package com.xopencode.netty.heima;

import io.netty.util.CharsetUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.CharSetUtils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author Mcb
 * @date 2022/5/21
 * @apiNote
 */
@Slf4j
public class AioFile {
    @SneakyThrows
    public static void main(String[] args) {
        try {
            AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("NioTest.txt"), StandardOpenOption.READ);
            ByteBuffer byteBuffer = ByteBuffer.allocate(16);
            log.debug("read begin...");
            /**
             * 参数1 buffer
             * 参数2 读取的起始位置
             * 参数3 附件，buffer读取不完再进行读取
             * 参数4 回调函数
             */
            channel.read(byteBuffer, 0, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                //回调线程为守护线程，主线程关闭后，守护线程会随之关闭
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("completed");
                    attachment.flip();
                    log.debug(new String(attachment.array(), CharsetUtil.UTF_8));
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    log.debug("failed");

                }
            });
            log.debug("read end...");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.in.read();
    }
}




















